package com.resou.reader.tinder;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mindorks.placeholderview.SwipeDecor;
import com.mindorks.placeholderview.SwipePlaceHolderView;
import com.mindorks.placeholderview.listeners.ItemRemovedListener;
import com.resou.reader.R;
import com.resou.reader.data.tinder.tinder.SlideBean;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.tinder.carddetail.CardDetailActivity;
import com.resou.reader.tinder.favorites.FavoritesActivity;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.StatusBarUtil;

import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.resou.reader.tinder.carddetail.CardDetailActivity.RESULT_DISLIKE;
import static com.resou.reader.tinder.carddetail.CardDetailActivity.RESULT_LIKE;

public class SwipeActivity extends AppCompatActivity implements ISwipeView {
    private static final String TAG = "SwipeActivity-App";

    public static final int REQUEST_SWIPE = 1;
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    @BindView(R.id.swipe_view)
    SwipePlaceHolderView swipeView;
    @BindView(R.id.rl_collect_or_not)
    RelativeLayout rlCollectOrNot;

    @BindView(R.id.rl_activity_swipe)
    RelativeLayout rlActivitySwipe;
    @BindView(R.id.progress_bar)
    LinearLayout progressBar;

    @BindView(R.id.tv_favorites_count)
    TextView tvFavoritesCount;
    @BindView(R.id.progress_bar_text)
    TextView progressBarText;
    @BindView(R.id.fl_error_container)
    FrameLayout flErrorContainer;

    private StatusBarUtil statusBarUtil = StatusBarUtil.getInstance();
    private List<SlideBean> mSlideBeans = new ArrayList<>();
    private boolean firstShow = true;
    private Throwable mThrowable;
    private SwipePresenter mPresenter;
    private String mToken = "";
    private boolean isLastSwipeIn;

    public static void startActivity(Context context) {
        Intent starter = new Intent(context, SwipeActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_swipe);
        ButterKnife.bind(this);

        mPresenter = new SwipePresenter(this);
        statusBarUtil.setUpStatusBar(this).build();

        tvToolbarTitle.setText("滑动选择你的喜欢的书籍");
        setupCardContainerView();

        mToken = UserInstance.getToken();
        mPresenter.getSwipeList(mToken);
        mPresenter.uploadLastPendingSubmissionSlideBean(mToken);
    }

    private void setupCardContainerView() {
        int screenWidth = ScreenUtils.getScreenWidth();
        int screenHeight = ScreenUtils.getScreenHeight();
        int paddingTop = (int) ScreenUtils.convertDpToPixel(18, this);
        swipeView.getBuilder()
                .setDisplayViewCount(3)
//                .setIsUndoEnabled(true)
                .setWidthSwipeDistFactor(7)
                .setIsUndoEnabled(true)
                .setHeightSwipeDistFactor(7)
                .setSwipeDecor(new SwipeDecor()
//                        .setSwipeMaxChangeAngle(2f)
                                .setViewWidth((int) (0.90 * screenWidth))
                                .setViewHeight((int) (0.80 * screenHeight))
                                //paddingTop指的是后层相对于前层的向下偏移量，越向下就越能看见后面SwipeDecor的内容
                                .setPaddingTop(paddingTop)
//                                .setSwipeAnimTime(80)
                                .setSwipeMaxChangeAngle(1)
                                .setSwipeInMsgLayoutId(R.layout.item_swipe_like)
                                .setSwipeInMsgGravity(Gravity.START)
                                .setSwipeOutMsgLayoutId(R.layout.item_swipe_dislike)
                                .setSwipeOutMsgGravity(Gravity.END)
                                .setRelativeScale(0.05f)
                );
        swipeView.addItemRemoveListener(new ItemRemovedListener() {
            //当每个项目被移除的时候回调此方法
            @Override
            public void onItemRemoved(int count) {
                //卡片被移除时删除列表第一个
                if (isLastSwipeIn) {
                    if (mPresenter.getBookIds() >= 20) {
                        onUndoClick();
                        return;
                    }
                }

                mSlideBeans.remove(0);

                //列表中项目低于5个，请求下一次数据
                if (count < 5) {
                    Log.d(TAG, "onItemRemoved: " + mSlideBeans.size() + " getNextSwipeList");
                    mPresenter.getNextSwipeList(mToken);
                }
                //校验列表的数量
                if (mSlideBeans.size() == 0) {
                    //为了重新添加数据时显示第一个的标题
                    firstShow = true;
                    //0表示没有数据，应该显示错误信息
                    //当页面包含错误信息时，mThrowable才不为null
                    if (mThrowable != null) {
                        showError(mThrowable);
                        return;
                    }
                    //不是网络错误，只是数据还没返回，应该显示进度条
                    showProgress();
                    return;
                }
                tvToolbarTitle.setText(mSlideBeans.get(0).getNovelName());
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        //读取之前保存的列表
        mPresenter.loadFavoritesCount();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //保存列表
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void addSwipeList(List<SlideBean> beans) {
        mSlideBeans.addAll(beans);
        for (SlideBean bean : beans) {
            swipeView.addView(new BookCard(swipeView, bean).setInteractionListener(mInteractionListener));
        }
        if (firstShow) {
            tvToolbarTitle.setText(mSlideBeans.get(0).getNovelName());
        }
        firstShow = false;
        showContent();
    }

    @Override
    public void showError(Throwable throwable) {
        if (throwable != null) {
            ErrorUtils.showErrorFragment(R.id.fl_error_container, getSupportFragmentManager(), new ErrorUtils.doNextCallback() {
                @Override
                public void retry() {
                    mPresenter.getSwipeList(mToken);
                }
            });
            if (throwable instanceof UnknownHostException
                    || throwable instanceof UnknownServiceException
                    || throwable instanceof TimeoutException) {
            }
        }
        tvToolbarTitle.setText("");
        progressBar.setVisibility(View.GONE);
        rlCollectOrNot.setVisibility(View.GONE);
        swipeView.setVisibility(View.GONE);
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
        rlCollectOrNot.setVisibility(View.GONE);
        swipeView.setVisibility(View.GONE);
    }

    @Override
    public void initData() {

    }

    @Override
    public void showContent() {
        tvToolbarTitle.setVisibility(View.VISIBLE);
        swipeView.setVisibility(View.VISIBLE);
        rlCollectOrNot.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void retry() {
    }

    @Override
    public void setError(Throwable throwable) {
        mThrowable = throwable;
    }

    @Override
    public int getCardListSize() {
        return mSlideBeans.size();
    }

    @Override
    public void showFavoritesCount(String count) {
        tvFavoritesCount.setText(count);
    }

    @OnClick(R.id.iv_back)
    void onBack() {
        finish();
    }

    @OnClick(R.id.iv_favorites)
    void onFavoritesClick() {
        FavoritesActivity.startActivity(this);
    }

    @OnClick(R.id.iv_dislike)
    void onRejectClick() {
        swipeView.doSwipe(false);
    }

    @OnClick(R.id.iv_like)
    void onAcceptClick() {
        swipeView.doSwipe(true);
    }

    @Override
    public void onUndoClick() {
        swipeView.undoLastSwipe();
    }

    /**
     * 此回调由卡片触发，当点击卡片、右滑和左滑调用对应的方法
     */
    private BookCard.onCardInteractionListener mInteractionListener = new BookCard.onCardInteractionListener() {
        /**
         * 不喜欢，告诉服务器不要再推荐这本书
         * @param slideBean
         */
        @Override
        public void onLeftSwiped(SlideBean slideBean) {
            // 丢弃，并且不再提示
            isLastSwipeIn = false;
        }

        /**
         * 喜欢，添加到收藏夹
         * @param slideBean
         */
        @Override
        public void onRightSwiped(SlideBean slideBean) {
            isLastSwipeIn = true;
            //添加到本地
            mPresenter.addToShoppingCart(slideBean, mToken);
        }

        @Override
        public void onCardClicked(SlideBean slideBean) {
            //跳转到第一章的详情页面
            Intent intent = CardDetailActivity.getStartIntent(SwipeActivity.this, slideBean);
            startActivityForResult(intent, REQUEST_SWIPE);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_SWIPE) {
            if (resultCode == RESULT_LIKE) {
                swipeView.doSwipe(true);
            }
            if (resultCode == RESULT_DISLIKE) {
                swipeView.doSwipe(false);
            }
        }
    }
}
